package com.fengniaoxls.fengniaonewretail.net.interceptor;


import com.fengniaoxls.fengniaonewretail.app.App;
import com.fengniaoxls.fengniaonewretail.commom.constants.Constants;
import com.fengniaoxls.fengniaonewretail.utils.SPUtils;

import java.io.IOException;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;


/**
 * 添加公共参数
 *
 * @author freak
 * @date 2019/9/11.
 */
public class CommonParametersInterceptor implements Interceptor {
    private String TAG = "CommonParametersInterceptor";

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request oldRequest = chain.request();
        Response response = null;
        //添加请求头
//        Request addParamRequest = addHeader(oldRequest);
        // 新的请求,添加参数
        Request newRequest = addParam(oldRequest);

        response = chain.proceed(newRequest);
        return response;
    }

    /**
     * 添加公共参数
     *
     * @param oldRequest
     * @return
     */
    private Request addParam(Request oldRequest) {
        if (oldRequest.url().toString().equals(Constants.getBaseUrl(Constants.SERVER_TYPE) + "routine/v1/goodsCategory/getGoodsList")) {
            return oldRequest;
        }
        HttpUrl.Builder builder = oldRequest.url()
                .newBuilder()
                .setEncodedQueryParameter("token", (String) SPUtils.get(App.getInstance().getApplicationContext(), Constants.ACCESS_TOKEN, ""));
        Request newRequest = oldRequest.newBuilder()
                .method(oldRequest.method(), oldRequest.body())
                .url(builder.build())
                .build();
        return newRequest;
    }

    /**
     * 添加请求头
     *
     * @param oldRequest
     * @return
     */
    public Request addHeader(Request oldRequest) {
        Request.Builder builder = oldRequest.newBuilder().addHeader("Content-Type", "application/json;charset=UTF-8")
                .post(RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), bodyToString(oldRequest.body())));
        return builder.build();
    }

    private static String bodyToString(final RequestBody request) {
        try {
            final RequestBody copy = request;
            final Buffer buffer = new Buffer();
            if (copy != null)
                copy.writeTo(buffer);
            else
                return "";
            return buffer.readUtf8();
        } catch (final IOException e) {
            return "did not work";
        }
    }

}
